﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Structs;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates an attribute.
    /// </summary>
    public class CreateLookupAttribute : CreateAuditable<LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SYS");
            }
        }

        /// <summary>
        /// Gets or sets the display order.
        /// </summary>
        public int DisplayOrder
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public LookupAttributeFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Construct(IUnitOfWork uow, LookupAttributeEntity entity)
        {
            base.Construct(uow, entity);

            entity.DisplayOrder = DisplayOrder;
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the attribute.
    /// </summary>
    public class UpdateLookupAttribute : UpdateAuditable<LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SYS");
            }
        }

        /// <summary>
        /// Gets or sets the display order.
        /// </summary>
        public int DisplayOrder
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public LookupAttributeFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Revise(IUnitOfWork uow, LookupAttributeEntity entity)
        {
            base.Revise(uow, entity);

            entity.DisplayOrder = DisplayOrder;
            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the attribute.
    /// </summary>
    public class DeleteLookupAttribute : DeleteEntity<LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SYS");
            }
        }

        #endregion

        #region Utilities

        protected override void Destruct(IUnitOfWork uow, LookupAttributeEntity entity)
        {
            foreach(var i in entity.Translations)
            {
                uow.Execute(new DeleteLookupAttributeTranslation
                {
                    EntityID = i.EntityID
                });
            }
            base.Destruct(uow, entity);
        }

        #endregion
    }

    /// <summary>
    /// Gets the attribute by identifier.
    /// </summary>
    public class GetLookupAttribute : GetEntity<LookupAttributeEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Translation__

    /// <summary>
    /// Creates an attribute translation.
    /// </summary>
    public class CreateLookupAttributeTranslation : CreateTranslation
        <TLookupAttributeEntity, LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SYS");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        public string Value
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Construct(IUnitOfWork uow, TLookupAttributeEntity entity)
        {
            base.Construct(uow, entity);

            entity.Value = StringHelper.EnsureNotNull(Value).TrimToLen(100);
            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
        }

        #endregion
    }

    /// <summary>
    /// Updates the attribute translation.
    /// </summary>
    public class UpdateLookupAttributeTranslation : UpdateTranslation
        <TLookupAttributeEntity, LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SYS");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        public string Value
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Revise(IUnitOfWork uow, TLookupAttributeEntity entity)
        {
            base.Revise(uow, entity);

            entity.Value = StringHelper.EnsureNotNull(Value).TrimToLen(100);
            entity.Name = StringHelper.EnsureNotNull(Name).TrimToLen(100);
        }

        #endregion
    }

    /// <summary>
    /// Saves an attribute translation.
    /// </summary>
    public class SaveLookupAttributeTranslation : SaveTranslation
        <TLookupAttributeEntity, LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SYS");
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        public string Value
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out TLookupAttributeEntity result)
        {
            var translation = uow.Execute(new GetLookupAttributeTranslationByLanguage
            {
                HolderID = HolderID,
                LanguageID = LanguageID
            }).Result;
            if(translation == null)
            {
                translation = uow.Execute(new CreateLookupAttributeTranslation
                {
                    HolderID = HolderID,
                    LanguageID = LanguageID,
                    Name = Name,
                    Value = Value
                }).Result;
            }
            else
            {
                translation = uow.Execute(new UpdateLookupAttributeTranslation
                {
                    EntityID = translation.EntityID,
                    LanguageID = LanguageID,
                    Name = Name,
                    Value = Value
                }).Result;
            }
            result = translation;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the attribute translation.
    /// </summary>
    public class DeleteLookupAttributeTranslation : DeleteTranlsation
        <TLookupAttributeEntity, LookupAttributeEntity>,
        ISecuredOperation, IApiOperation
    {
        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SYS");
            }
        }
    }

    /// <summary>
    /// Gets the attribute translation.
    /// </summary>
    public class GetLookupAttributeTranslation : GetTranlsation
        <TLookupAttributeEntity, LookupAttributeEntity>,
        IApiOperation
    {
    }

    /// <summary>
    /// Gets the attribute translation.
    /// </summary>
    public class GetLookupAttributeTranslationByLanguage : GetTranlsationByLanguage
        <TLookupAttributeEntity, LookupAttributeEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over attribute collection.
    /// </summary>
    public class SearchLookupAttributes : SearchOperation<LookupAttributeEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchLookupAttributes()
        {
            Term = SearchTerm.Empty;
            SortDir = SortDirection.Ascending;
            SortBy = new []
            {
                LookupAttributeSortBy.ID
            };
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the search term.
        /// </summary>
        public SearchTerm Term
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the language identifier.
        /// </summary>
        public int? LanguageID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public LookupAttributeFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort by.
        /// </summary>
        public LookupAttributeSortBy[] SortBy
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<LookupAttributeEntity> Build(IUnitOfWork uow, IQueryable<LookupAttributeEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            switch(Term.Mode)
            {
                case SearchTerm.SearchMode.StartsWith:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                                i.Name.StartsWith(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Name.StartsWith(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.EndsWith:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                                i.Value.EndsWith(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Value.EndsWith(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.Contains:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                                (i.Value.Contains(Term.Keyword) ||
                                    i.Name.Contains(Term.Keyword))));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Value.Contains(Term.Keyword) ||
                                i.Name.Contains(Term.Keyword)));
                    break;
                case SearchTerm.SearchMode.Equals:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Language.EntityID == LanguageID.Value &&
                                i.Value.Equals(Term.Keyword)));
                    else
                        query = query.Where(x => x.Translations.Any(i =>
                            i.Value.Equals(Term.Keyword)));
                    break;
                default:
                    if(LanguageID.HasValue)
                        query = query.Where(x => x.Translations.Any(i => i.Language.EntityID == LanguageID.Value));
                    break;
            }
            if(SortBy != null)
            {
                for(int i = 0; i < SortBy.Length; i++)
                {
                    switch(SortBy[i])
                    {
                        case LookupAttributeSortBy.DisplayOrder:
                            query = query.OrderBy(x => x.DisplayOrder, SortDir, i != 0);
                            break;
                        case LookupAttributeSortBy.CreatedOn:
                            query = query.OrderBy(x => x.CreatedOn, SortDir, i != 0);
                            break;
                        default:
                            query = query.OrderBy(x => x.EntityID, SortDir, i != 0);
                            break;
                    }
                }
            }
            return query;
        }

        #endregion
    }

    /// <summary>
    /// Gets the collection of attributes as a dictionary, where 
    /// key - attribute identifier and value - attribute name:value.
    /// </summary>
    public class GetLookupAttributeDictionary : SearchOperation<TLookupAttributeEntity, Int32, String>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public GetLookupAttributeDictionary()
        {
            Term = SearchTerm.Empty;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the language identifier.
        /// </summary>
        public int LanguageID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the search term.
        /// </summary>
        public SearchTerm Term
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public LookupAttributeFlags FlagMask
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<TLookupAttributeEntity> Build(IUnitOfWork uow, IQueryable<TLookupAttributeEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => (int)x.Holder.Flags, (int)FlagMask);
            query = query.Where(x => x.Language.EntityID == LanguageID);
            switch(Term.Mode)
            {
                case SearchTerm.SearchMode.StartsWith:
                    query = query.Where(x => x.Name.StartsWith(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.EndsWith:
                    query = query.Where(x => x.Value.EndsWith(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.Contains:
                    query = query.Where(x =>
                        x.Value.Contains(Term.Keyword) ||
                        x.Name.Contains(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.Equals:
                    query = query.Where(x => x.Value.Equals(Term.Keyword));
                    break;
            }
            query = query.OrderBy(x => x.Value);
            return query;
        }

        protected override IQueryable<KeyValuePair<Int32, String>> Map(IQueryable<TLookupAttributeEntity> query)
        {
            return query.Select(x => new KeyValuePair<Int32, String>(x.Holder.EntityID, String.Format("{0}: {1}", x.Name, x.Value)));
        }

        #endregion
    }

    #endregion
}
